package codetop.microsoft.T138;

/**
 * @Author: 18362
 * @Create: 2022-08-19 8:25:08 星期五
 */
class Solution {
    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        if (head == null)
            return null;
        Node p = head;
        while (p != null) {
            Node t = new Node(p.val);
            t.next = p.next;
            p.next = t;
            p = t.next;
        }
        p = head;
        while (p != null) {
            Node t = p.next;
            if (p.random != null)
                t.random = p.random.next;
            p = t.next;
        }
        Node tHead = new Node(0), q = tHead;
        p = head;
        while (p != null) {
            Node t = p.next;
            p.next = t.next;
            q.next = t;
            q = q.next;
            p = p.next;
        }
        return tHead.next;
    }
}
